// pages/category/category.js
import {Category} from 'category-model.js';
var category = new Category();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    'selectIndex': 0,
    'loadedData': {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.__loadData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  __loadData: function () {

    // 获取商品分类列表
    category.getProductCategory((res) => {
      this.setData({
        categoryArr:res
      });
      
      // 获取默认第一个分类的商品数据
      if (res[0]) {
        category.getProductByCategory(res[0].id, (productData) => {
          var dataObj = {
            title: res[0].name,
            topImgUrl: res[0].img.url,
            products: productData
          }
          this.setData({
            categoryProductsArr: dataObj,
          })

          this.data.loadedData[0] = dataObj;
        });
      }
    });
  },

  // 检查是否已经加载过该数据
  isloadedData: function(index) {
    if (!this.data.loadedData[index]){
      return false;
    }
    else {
      return true;
    }
  },

  // 根据分类获取商品列表
  getProductByCategory: function(event) {
    var index = category.getDataSet(event, 'index');
    var categoryId = category.getDataSet(event, 'id');

    // 设置index
    this.setData({
      selectIndex: index
    })

    if (!this.isloadedData(index)) {
      category.getProductByCategory(categoryId, (productData) => {
        var dataObj = {
          title: this.data.categoryArr[index].name,
          topImgUrl: this.data.categoryArr[index].img.url,
          products: productData
        }
        this.setData({
          categoryProductsArr: dataObj,
        })
        this.data.loadedData[index] = dataObj;
      });
    }
    else {
      this.setData({
        categoryProductsArr: this.data.loadedData[index],
      })
    }
  },

  // 点击商品跳转商品详情列表
  onProductsItemTap: function (event) {
    var productId = category.getDataSet(event, 'id');
    wx.navigateTo({
      url: '../product/product?productId=' + productId,
    })
  }
  
})